package cn.good.yan.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义单一过滤器
 * 访问 http://localhost:9527/g/gateway/filter 接口 失败，因为没有参数名是 yy
 * 访问 http://localhost:9527/g/gateway/filter?yy 接口 成功，有参数yy，就可以，没有yy就不可以访问，并不关心yy里的值
 *
 * @author shengren.yan
 * @create 2024-05-10
 */
@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.Config> {

    public MyGatewayFilterFactory() {
        super(MyGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(MyGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 得到请求头
                ServerHttpRequest request = exchange.getRequest();
                System.out.println("进入了自定义网关过滤器 - yml中配置的status：" + config.getStatus());
                // 如果参数yy，进行放行，没有返回 - 回应头
                if (request.getQueryParams().containsKey("yy")) {
                    return chain.filter(exchange);
                } else {
                    exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                    return exchange.getResponse().setComplete();
                }
            }
        };
    }

    // 如果不配置这个，需要yml这里，需要全写，参考 断言的
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("status");
    }

    public static class Config {
        @Getter
        @Setter
        private String status; //设定一个状态值/标志位，它等于多少，匹配和才可以访问
    }

}
